//
//  SimpleNetworkTests.swift
//  SimpleNetworkTests
//
//  Created by gongtao on 15/3/5.
//  Copyright (c) 2015年 _organizeation. All rights reserved.
//

import UIKit
import XCTest

class SimpleNetworkTests: XCTestCase {
    
    let net = SimpleNetwork()
    let URLString = "http://httpbin.org/get"
    
    override func setUp() {
        super.setUp()
    }
    
    override func tearDown() {
        super.tearDown()
    }
    
    //测试参数拼接函数是否正确
    func testChangeParamsToQuery() {
        //测试不传入拼接内容是否返回空值
        XCTAssertNil(net.changeParamsToQuery(nil), "查询值应该为空")
        //测试传入一个参数拼接是否正确
        XCTAssert(net.changeParamsToQuery(["key": "value"]) == "key=value", "传入单个参数拼接不正确")
        //测试传入多个参数拼接是否正确
        XCTAssert(net.changeParamsToQuery(["key1": "value1", "key2": "value2"]) == "key1=value1&key2=value2", "传入多个参数拼接不正确")
        //测试百分号转义拼接是否正确
        XCTAssert(net.changeParamsToQuery(["键": "值"]) == "键&值".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding), "百分号转义拼接不正确")
    }
    
    //测试GET请求返回和参数拼接是否正确
    func testRequestJSONGET() {
        //测试不填写拼接参数是否返回空请求
        var request = net.setUpURLRequest(.GET, "", nil)
        XCTAssertNil(request, "不填写拼接参数应该返回空请求")
        
        //测试拼接参数是否返回请求
        request = net.setUpURLRequest(.GET, URLString, nil)
        XCTAssertNotNil(request, "填写拼接参数应该返回请求")
        //测试不拼接参数内容返回的URL是否正确
        request = net.setUpURLRequest(.GET, URLString, nil)
        XCTAssert(request!.URL!.absoluteString == URLString, "不拼接参数内容返回的URL不正确")
        //测试拼接参数内容返回的URL是否正确
        request = net.setUpURLRequest(.GET, URLString, ["key": "value"])
        XCTAssert(request!.URL!.absoluteString == URLString + "?key=value", "拼接参数内容返回的URL不正确")
    }
    
    //测试POST请求的返回、参数拼接、数据体内容是否正确
    func testRequestJSONPOST() {
        //测试不填写拼接参数是否返回空请求
        var request = net.setUpURLRequest(.POST, URLString, nil)
        XCTAssertNil(request, "不填写拼接参数应该返回空请求")
        
        //测试拼接参数是否返回请求
        request = net.setUpURLRequest(.POST, URLString, ["key": "value"])
        XCTAssertNotNil(request, "填写拼接参数应该返回请求")
        //测试访问的方法是否正确
        XCTAssert(request!.HTTPMethod == "POST", "访问的方法应该是POST")
        //测试请求数据体内容是否正确
        XCTAssert(request!.HTTPBody == "key=value".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true), "请求的数据体内容不正确")
    }
    
    //测试requestJSON函数是否执行回调
    func testRequestJSONCompletion() {
        let expection = expectationWithDescription(URLString)
        net.requestJSON(.GET, URLString, nil) { (result, error) -> () in
            println(result)
            expection.fulfill()
        }
        waitForExpectationsWithTimeout(10.0, handler: { (error) -> Void in
            XCTAssertNil(error, "requestJSON函数回调没有执行")
        })
    }
    
    //测试RequestJSON函数是否返回错误信息
    func testRequestJSONError() {
        net.requestJSON(.GET, "", nil) { (result, error) -> () in
            XCTAssertNotNil(error, "需要返回错误信息")
        }
    }
}


